package com.copyctrl.campus.portal.controller;

import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.constant.HttpConstant;
import com.copyctrl.campus.common.constant.RedisConstant;
import com.copyctrl.campus.common.domain.User;
import com.copyctrl.campus.common.model.ApiResponse;
import com.copyctrl.campus.portal.service.UserService;
import com.copyctrl.model.CampUser;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author:JH
 * @version:1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/get")
    public ApiResponse getUser(HttpServletRequest request){
        String openid = request.getHeader(HttpConstant.USER);
        //从请求头中获取User，再从redis中获取用户信息
        String userJson = stringRedisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        return ApiResponse.ofSuccess(user);
    }

    @PutMapping("/update/{user}")
    public ApiResponse updateUser(HttpServletRequest request, @PathVariable String user){
        CampUser user1 = JSONUtil.toBean(user, CampUser.class);
        user1.setOpenid(request.getHeader(HttpConstant.USER));
        boolean b = userService.updateUser(user1);
        return b?ApiResponse.ofSuccess(""):ApiResponse.ofFailure("系统内部错误");
    }

    @GetMapping("/get/{id}")
    public ApiResponse getUserById(@PathVariable Integer id){
        String openid =stringRedisTemplate.opsForHash().get(RedisConstant.ID_OPENID,id.toString()).toString();
        //从请求头中获取User，再从redis中获取用户信息
        String userJson = stringRedisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        return ApiResponse.ofSuccess(user);
    }

}
